import { Component, OnInit, OnChanges, Input, Output, EventEmitter, SimpleChanges, OnDestroy } from '@angular/core';
import { MatDialog } from '@angular/material';
import { RestService } from '../../services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { AlarmDialogComponent } from '../alarm-dialog/alarm-dialog.component';
import { BhhistDialogComponent } from '../bhhist-dialog/bhhist-dialog.component';
import { environment } from 'environments/environment';

import * as _ from 'lodash';

const BEDLINK = ' ';

@Component({
  selector: 'app-cobject',
  templateUrl: './cobject.component.html',
  styleUrls: ['./cobject.component.css']
})
export class CobjectComponent implements OnInit, OnChanges, OnDestroy {
  refreshInterval = environment.interval;
  institution: any;
  interval;
  options: any;

  bChartOptions;
  bEchartsInstance;
  bTitle;

  hChartOptions;
  hEchartsInstance;
  hTitle;

  awayAlarm = '-';
  sideAlarm = '-';
  breatheAlarm = '-';
  heartAlarm = '-';
  wetAlarm = '-';

  bedNumber = '';
  building = '';

  @Input() person: any;
  @Output() hide = new EventEmitter<any>();

  constructor(private rest: RestService, private translate: TranslateService, private dialog: MatDialog) {
    this.bTitle = this.translate.get('breathe')['value'];
    this.hTitle = this.translate.get('heart')['value'];
  }

  parseBedString(bedString) {
    if (!bedString) {
      this.bedNumber = '-';
      this.building = '-';
      return;
    }

    const beds = bedString.split('##');
    this.bedNumber = beds.pop();
    this.building = beds.join(BEDLINK);
  }

  hideIt() {
    if (this.interval) {
      clearInterval(this.interval);
    }

    this.hide.emit();
  }

  initChart() {
    this.bChartOptions = _.cloneDeep(this.options);
    this.bChartOptions.title.text = this.bTitle;
    this.bChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.breatheUp},
      {name: 'lower', yAxis: this.person.breatheLow},
    ];

    this.hChartOptions = _.cloneDeep(this.options);
    this.hChartOptions.title.text = this.hTitle;
    this.hChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.heartUp},
      {name: 'lower', yAxis: this.person.heartLow},
    ];
  }

  onBChartInit(ec) {
    this.bEchartsInstance = ec;
    ec.setOption(this.bChartOptions);
  }

  onHChartInit(ec) {
    this.hEchartsInstance = ec;
    ec.setOption(this.hChartOptions);
  }

  startRoutine() {
    this.initData();
    this.interval = setInterval(() => {
      this.initData();
    }, this.refreshInterval);
  }

  getSecondsFromLast8Am() {
    let hour = new Date().getHours();
    hour = hour >= 8 ? (hour - 8) : (24 + hour - 8);
    return hour * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds() - 1;
  }

  buildEmptyData(startTime, endTime, step) {
    const data = [[startTime * 1000, ''], [endTime * 1000, '']];
    return data;
  }

  initData() {
    const endTime = new Date().getTime() / 1000;
    const startTime = endTime - 60 * 60;
    const step = 5;
    this.rest.getWithParams('api/v1/query_range', {
      query: 'breathe{personId="' + this.person.id + '"}',
      start: startTime,
      end: endTime,
      step: step,
      timeout: 4
    }).subscribe(resp => {
      if (resp['status'] === 'success') {
        if (resp['data']['result'].length < 1) {
          this.bChartOptions.title.text = this.bTitle;
          this.bChartOptions.title.textStyle.color = 'darkblue';
          this.bChartOptions.series[0].data = this.buildEmptyData(startTime, endTime, step);
          this.bEchartsInstance.setOption(this.bChartOptions);
          return;
        }

        const data = resp['data']['result'][0].values;
        data.forEach(item => {
          item[0] = item[0] * 1000;
        });
        this.bChartOptions.series[0].data = data;
        let currentValue = data[data.length - 1][1];
        if (currentValue.length === 1) {
          currentValue = '0' + currentValue;
        }
        this.bChartOptions.title.text = this.bTitle + ' ' + currentValue;
        currentValue = _.toNumber(currentValue);
        if (currentValue < this.person.breatheLow || currentValue > this.person.breatheUp) {
          this.bChartOptions.title.textStyle.color = 'darkred';
        } else {
          this.bChartOptions.title.textStyle.color = 'darkgreen';
        }
        this.bEchartsInstance.setOption(this.bChartOptions);
      }
    });

    this.rest.getWithParams('api/v1/query_range', {
      query: 'heart{personId="' + this.person.id + '"}',
      start: startTime,
      end: endTime,
      step: step,
      timeout: 4
    }).subscribe(resp => {
      if (resp['status'] === 'success') {
        if (resp['data']['result'].length < 1) {
          this.hChartOptions.title.text = this.hTitle;
          this.hChartOptions.title.textStyle.color = 'darkblue';
          this.hChartOptions.series[0].data = this.buildEmptyData(startTime, endTime, step);
          this.hEchartsInstance.setOption(this.hChartOptions);
          return;
        }

        const data = resp['data']['result'][0].values;
        data.forEach(item => {
          item[0] = item[0] * 1000;
        });
        this.hChartOptions.series[0].data = data;
        let currentValue = data[data.length - 1][1];
        if (currentValue.length === 1) {
          currentValue = '0' + currentValue;
        }
        this.hChartOptions.title.text = this.hTitle + ' ' + currentValue;
        currentValue = _.toNumber(currentValue);
        if (currentValue < this.person.heartLow || currentValue > this.person.heartUp) {
          this.hChartOptions.title.textStyle.color = 'darkred';
        } else {
          this.hChartOptions.title.textStyle.color = 'darkgreen';
        }
        this.hEchartsInstance.setOption(this.hChartOptions);
      }
    });

    this.rest.getWithParams('api/pro/allAlarmCounters', {
      personId: this.person.id,
      interval: this.getSecondsFromLast8Am()
    }).subscribe(resp => {
      this.breatheAlarm = resp['breatheAlarm'];
      this.heartAlarm = resp['heartAlarm'];
      this.awayAlarm = resp['awayAlarm'];
      this.wetAlarm = resp['wetAlarm'];
      this.sideAlarm = resp['move'];
    });
  }

  openAlarm(alarm) {
    this.dialog.open(AlarmDialogComponent, {
      disableClose: true,
      autoFocus: false,
      width: '800px',
      data: {
        person: this.person,
        alarm: alarm
      }
    });
  }

  openHistDialog() {
    this.dialog.open(BhhistDialogComponent, {
      disableClose: true,
      autoFocus: false,
      width: '1024px',
      data: {
        person: this.person
      }
    });
  }

  ngOnInit() {
    this.parseBedString(this.person.bedString);
    this.options = {
      title: {
        text: '',
        subtext: this.translate.get('heartUnit')['value'],
        subtextStyle: {color: 'black'},
        x: 'left',
        y: 'top',
        textStyle: {
          color: 'darkblue'
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          return new Date(params[0].data[0]).toLocaleString() + '<br>' + params[0].data[1] + ' ' + this.translate.get('heartUnit')['value'];
        }
      },
      grid: {
        x: '80',
        y: '10',
        x2: '30',
        y2: '0',
        containLabel: true
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: true
        }
      },
      yAxis: {
        type : 'value',
        boundaryGap: false,
        splitLine: {
          show: true
        }
      },
      series: [{
        type: 'line',
        showSymbol: false,
        markLine: {
          itemStyle: {
            normal: {
              lineStyle: {
                type: 'dashed',
                color: 'darkred'
              }
            }
          },
          data: []
        },
        data: []
      }]
    };

    this.initChart();

    setTimeout(() => {
      this.hEchartsInstance.resize();
      this.startRoutine();
    }, 100);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes && changes.person && this.bEchartsInstance && this.hEchartsInstance) {
      // reinit the charts
      if (this.interval) {
        clearInterval(this.interval);
      }

      this.ngOnInit();
      this.bEchartsInstance.setOption(this.bChartOptions);
      this.hEchartsInstance.setOption(this.hChartOptions);
    }
  }

  ngOnDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }
}
